package org.diysearch.products;

import java.io.OutputStream;
import java.io.Writer;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.exceptions.ObjectNotSupportedException;
import org.diysearch.interfaces.Model;
import org.diysearch.tools.StringTools;
import org.json.JSONObject;

public class JsonProduct extends BaseProduct {
	private static final Log LOG = LogFactory.getLog(JsonProduct.class);
	private String content;
	private JspWriter out;
	
	@Override
	public String getContentType() {
		// TODO Auto-generated method stub
		return "text/plain";
	}

	@Override
	public void print() {
		try {
			out.print(content);
		} catch (Exception ex) {
			LOG.error("Could not print output: " + StringTools.getStackTrace(ex));
		}

	}

	@Override
	public void setContentType(String ct) {

	}

	@Override
	public void setOutput(Object output) throws ObjectNotSupportedException {
		if (output instanceof Model) {
			Model m = (Model)output;
			content = new JSONObject(m.toMap()).toString();
		} else {
			throw new ObjectNotSupportedException ("Only Models can be set as output");
		}

	}

	@Override
	public void setOutputStream(OutputStream outputStream) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setWriter(Writer writer) {
		this.out = (JspWriter) writer;
	}

}
